package com.ikingtech.platform.service.system.organization.service;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ikingtech.framework.sdk.base.model.PageResult;
import com.ikingtech.framework.sdk.context.exception.FrameworkException;
import com.ikingtech.framework.sdk.organization.model.OrganizationQueryParamDTO;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.service.system.organization.entity.OrganizationDO;
import com.ikingtech.platform.service.system.organization.exception.OrganizationExceptionInfo;
import com.ikingtech.platform.service.system.organization.mapper.OrganizationMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author tie yan
 */
@Service
@AllArgsConstructor
@Slf4j
public class OrganizationService extends ServiceImpl<OrganizationMapper, OrganizationDO> {

    public String parseFullPath(String parentId, String id) {
        if (Tools.Str.isNotBlank(parentId)) {
            OrganizationDO parentEntity = this.getById(parentId);
            if (null == parentEntity) {
                throw new FrameworkException(OrganizationExceptionInfo.PARENT_ORG_NOT_FOUND);
            }
            return createFullPath(parentEntity.getFullPath(), id);
        } else {
            return id;
        }
    }

    private String createFullPath(String fullPath, String id) {
        if (Tools.Str.isBlank(fullPath)) {
            return id;
        }
        return fullPath + "@" + id;
    }

    public boolean exist(String id) {
        return this.baseMapper.exists(Wrappers.<OrganizationDO>lambdaQuery().eq(OrganizationDO::getId, id));
    }

    public PageResult<OrganizationDO> listPage(OrganizationQueryParamDTO queryParam, List<String> dataScopeCodes, String tenantCode) {
        return PageResult.build(this.page(new Page<>(queryParam.getPage(), queryParam.getRows()),this.createQueryWrapper(queryParam, dataScopeCodes, tenantCode)));
    }

    public List<String> listIdByFullPath(String fullPath) {
        return this.listObjs(Wrappers.<OrganizationDO>lambdaQuery()
                .select(OrganizationDO::getId)
                .likeRight(OrganizationDO::getFullPath, fullPath), String.class::cast);
    }

    public Integer getMaxSortOrder(String parentId) {
        List<Number> orders = this.listObjs(Wrappers.<OrganizationDO>query().lambda().select(OrganizationDO::getSortOrder).eq(OrganizationDO::getParentId, parentId).orderByDesc(OrganizationDO::getSortOrder), Number.class::cast);
        return Tools.Coll.isBlank(orders) ? 0 : orders.get(0).intValue();
    }

    public <T> List<OrganizationDO> between(Object parentId, T startValue, T endValue) {
        return this.list(Wrappers.<OrganizationDO>query().lambda()
                .eq(OrganizationDO::getParentId, parentId)
                .between(OrganizationDO::getSortOrder, startValue, endValue)
        );
    }

    public List<OrganizationDO> gt(Object parentId, Object value) {
        return this.list(Wrappers.<OrganizationDO>query().lambda()
                .eq(OrganizationDO::getParentId, parentId)
                .gt(OrganizationDO::getSortOrder, value)
                .orderByAsc(OrganizationDO::getSortOrder)
        );
    }

    public List<String> listIdsByFullPaths(List<String> fullPaths) {
        if (Tools.Coll.isBlank(fullPaths)) {
            return new ArrayList<>();
        }
        return this.listObjs(Wrappers.<OrganizationDO>lambdaQuery()
                .or(wrapper -> fullPaths.forEach(fullPath -> wrapper.likeRight(OrganizationDO::getFullPath, fullPath))), String.class::cast);
    }

    public List<OrganizationDO> listByParentId(String parentId) {
        return this.list(Wrappers.<OrganizationDO>lambdaQuery().eq(OrganizationDO::getParentId, parentId));
    }

    public List<OrganizationDO> listByName(String name, String tenantCode) {
        return this.list(Wrappers.<OrganizationDO>lambdaQuery()
                .like(OrganizationDO::getName, name)
                .eq(OrganizationDO::getTenantCode, tenantCode)
                .orderByDesc(OrganizationDO::getCreateTime));
    }

    public List<OrganizationDO> listByTenantCode(String tenantCode) {
        return this.list(Wrappers.<OrganizationDO>lambdaQuery().eq(OrganizationDO::getTenantCode, tenantCode));
    }

    public List<OrganizationDO> listByCondition(OrganizationQueryParamDTO queryParam, List<String> dataScopeCodes, String tenantCode) {
        return this.list(this.createQueryWrapper(queryParam, dataScopeCodes, tenantCode));
    }

    private LambdaQueryWrapper<OrganizationDO> createQueryWrapper(OrganizationQueryParamDTO queryParam, List<String> dataScopeCodes, String tenantCode) {
        return Wrappers.<OrganizationDO>lambdaQuery()
                .in(Tools.Coll.isNotBlank(dataScopeCodes), OrganizationDO::getId, dataScopeCodes)
                .like(Tools.Str.isNotBlank(queryParam.getName()), OrganizationDO::getName, queryParam.getName())
                .like(Tools.Str.isNotBlank(queryParam.getPhone()), OrganizationDO::getPhone, queryParam.getPhone())
                .like(Tools.Str.isNotBlank(queryParam.getFax()), OrganizationDO::getFax, queryParam.getFax())
                .like(Tools.Str.isNotBlank(queryParam.getAddress()), OrganizationDO::getAddress, queryParam.getAddress())
                .eq(Tools.Str.isNotBlank(tenantCode), OrganizationDO::getTenantCode, tenantCode)
                .orderByAsc(OrganizationDO::getGrade)
                .orderByAsc(OrganizationDO::getSortOrder);
    }

    public void removeByTenantCode(String tenantCode) {
        this.remove(Wrappers.<OrganizationDO>lambdaQuery().eq(OrganizationDO::getTenantCode, tenantCode));
    }

    public List<String> listIdByTenantCode(String tenantCode) {
        return this.listObjs(Wrappers.<OrganizationDO>lambdaQuery().eq(OrganizationDO::getTenantCode, tenantCode), String.class::cast);
    }

    public List<String> listIdsByFullPath(String fullPath) {
        return this.listObjs(Wrappers.<OrganizationDO>lambdaQuery()
                .select(OrganizationDO::getId)
                .likeRight(OrganizationDO::getFullPath, fullPath), String.class::cast);
    }

    public List<OrganizationDO> listSubByFullPaths(List<String> fullPaths) {
        if(Tools.Coll.isBlank(fullPaths)){
            return new ArrayList<>();
        }
        return this.list(Wrappers.<OrganizationDO>lambdaQuery()
                .or(wrapper -> fullPaths.forEach(fullPath -> wrapper.likeRight(OrganizationDO::getFullPath, fullPath)))
                .orderByDesc(OrganizationDO::getCreateTime));
    }
}
